<?php

/**
 * SQLRow Result
 *
 * @version $Id$
 * @copyright 2010
 */

/**
 * SQLRow
 *
 */
class SQLRow extends sqld{
	private $row;
	private $set;
	private $where;
	private $table;

	/**
	 * Constructor
	 */
	function __construct($row, $primary, $table){
		if ($primary !== false)
		{
			$this->where = 'WHERE `'.$primary.'` = \''.$this->escape($row[$primary]).'\'';
		}
		else
		{
			$this->where = false;
		}
		
		$this->row = $row;
		$this->table = $table;
		$this->set = array();
	}

	function __get($var)
	{
		if (in_array($var, array_keys($this->set)))
		{
			return $this->set[$var];
		}
		elseif (in_array($var, array_keys($this->row)))
		{
			return $this->row[$var];
		}
		else
		{
			return false;
		}
	}

	function __set($var, $value)
	{
		if ($this->where === false)
		{
			throw new CoreException('You try to set a value in a SQL view.');
		}
		elseif (!in_array($var, array_keys($this->row)))
		{
			throw new ArgError('Field not in query');
		}
		elseif ($value == $this->row[$var])
		{
			unset($this->set[$var]);
		}
		else
		{
			$this->set[$var] = $value;
		}
	}

	function __destruct()
	{
		if (count($this->set) > 0)
		{
			$query = 'UPDATE `'.$this->table.'` SET `';
			foreach ($this->set as $key => $value){
				if ($value !== null)
					$query .= $key . '` = \'' . $this->escape($value) . '\', `';
				else
					$query .= $key . '` = NULL, `';
			}
			$query = substr($query, 0, -3);
			$query .= ' ' . $this->where;
			echo $query;
			$this->query($query);
		}
		//Change row
	}
}
?>
